package leetcode.new_wrold;

public class T48 {
    public void rotate(int[][] matrix) {
        int n = matrix.length/2;    //1
        for (int i = 0;i < n;i++){
            rotateCycle(i,matrix,matrix.length);
        }

        for (int[] num : matrix) {
            for (int i : num) {
                System.out.print(i+" ");
            }
            System.out.println();
        }

    }

    private void rotateCycle(int cycle,int[][] matrix,int n){
        System.out.println("========");
        System.out.println("cycle="+cycle);
        int length = n-cycle*2; //  3
        int left = cycle;   //0
        int right = left+length-1;  //5
        int top = cycle;        //0
        int bottom = top+length-1;  //5
        System.out.println("left ="+left+",right="+right+",top="+top+",bottom="+bottom);

        for (int j = left;j<right;j++){
            int a = matrix[j][right];//右
            matrix[j][right] = matrix[top][j];
            System.out.println("i ="+j+",j="+right+",num="+matrix[top][j]);

            int b = matrix[bottom][n-1-j];  //下
            matrix[bottom][n-1-j] = a;
            System.out.println("i ="+bottom+",j="+(n-1-j)+",num="+a);

            int c = matrix[n-1-j][left];      //左
            matrix[n-1-j][left] = b;
            System.out.println("i ="+(n-1-j)+",j="+left+",num="+b);


            matrix[top][j] = c;   //上
            System.out.println("i ="+top+",j="+j+",num="+c);

        }
        System.out.println("========");
    }

    public static void main(String[] args) {
        T48 t48 = new T48();
        int[][] nums = {
                {1, 2, 3,4},
                {5, 6, 7,8},
                {9, 10, 11,12},
                {13,14,15,16}
        };
        t48.rotate(nums);

        for (int[] num : nums) {
            for (int i : num) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
}
